package jeecg.hh.mvc.classloader;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import jeecg.hh.mvc.annotation.RequstMapping;
import jeecg.hh.mvc.annotation.Resource;


public class AnnotationParse {
	
	protected static void parseAnnotation(String name) throws ClassNotFoundException {
		// 获取当前线程上下文类加载器
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		try {
			// 设置当前线程上下文类加载器为targetTccl
			try {
				Thread.currentThread().setContextClassLoader(AnnotationClassloader.class.newInstance());
				//初始化注解
				initResourceAnnotation(name);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		} finally {// 设置当前线程上下文加载器为原始加载器
			Thread.currentThread().setContextClassLoader(classLoader);
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static void initResourceAnnotation(String name){
		ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
		try {
			Object object=Class.forName(name).newInstance();
			Class clazz=classLoader.loadClass(name);
			Field[] fieldList=clazz.getDeclaredFields();
			for (Field field : fieldList) {
				field.setAccessible(true);
				if(field.isAnnotationPresent(Resource.class)){
					field.set(object,field.getType().newInstance());
				}
				field.setAccessible(false);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static void initRequestMappingAnnotation(
//			Class<?> clazz,
			String name,String requestPath){
		ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
		try {
			Class clazz=classLoader.loadClass(name);
			Method[] MethodList=clazz.getDeclaredMethods();
			for (Method method : MethodList) {
				if(method.isAnnotationPresent(RequstMapping.class)){
					RequstMapping requstMapping=method.getAnnotation(RequstMapping.class);
					if(requstMapping.value().equals(requestPath)){
						method.invoke(clazz.newInstance(), method.getParameters());
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
